var global = {fullscreen:0,difficulty:0};
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 获取DOM元素
    const card = document.querySelector('.card');
    const autoBtn = document.getElementById('autoBtn');
    const flipBtn = document.getElementById('flipBtn');
    const nextBtn = document.getElementById('nextBtn');
    const progressSpan = document.getElementById('currentProgress');
    
    // 当前单词索引
    let currentIndex = 0;
    // 打乱的单词数组
    let shuffledWords = [];

    // Fisher-Yates 洗牌算法
    function shuffleArray(array) {
        let currentIndex = array.length;
        let temporaryValue, randomIndex;

        while (currentIndex !== 0) {
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array;
    }

    // 初始化打乱的单词数组
    function initializeWords() {
        shuffledWords = shuffleArray([...words]);
        displayWord(0);
        updateProgress();
    }

    // 显示单词
    function displayWord(index) {
        const word = shuffledWords[index];
        
        // 更新正面内容
        document.querySelector('.card-front .word').textContent = word.word;
        document.querySelector('.card-front .phonetic').textContent = word.phonetic;

        // 确保卡片显示正面
        card.classList.remove('flipped');
        
        // 延迟一秒
        setTimeout(() => {
            // 更新背面内容
            document.querySelector('.card-back .word').textContent = word.word;
            document.querySelector('.card-back .phonetic').textContent = word.phonetic;
            document.querySelector('.card-back .meaning').textContent = word.meaning;
            document.querySelector('.card-back .example').textContent = word.example;
        }, 500);
    }

    // 更新进度显示
    function updateProgress() {
        progressSpan.textContent = `${currentIndex + 1}/${shuffledWords.length}`;
    }

    // 翻转卡片
    function flipCard() {
        card.classList.toggle('flipped');
    }

    // 下一个单词
    function nextWord() {
        currentIndex = (currentIndex + 1) % shuffledWords.length;
        displayWord(currentIndex);
        updateProgress();
    }

    // 随机切换到新单词
    function randomWord() {
        let newIndex;
        do {
            newIndex = Math.floor(Math.random() * shuffledWords.length);
        } while (newIndex === currentIndex && shuffledWords.length > 1);
        
        currentIndex = newIndex;
        displayWord(currentIndex);
        updateProgress();
    }

    let auto_status = 0;
    let ob = null;
    // 自动下一个
    autoBtn.addEventListener('click', function() {
        if(auto_status == 0){
            auto_status = 1;
            autoBtn.innerHTML = '停止';
            ob = setInterval(() => {
                flipCard();
                setTimeout(() => {
                    nextWord();
                }, 2500);
            }, 5500);
        }else{
            autoBtn.innerHTML = '自动';
            auto_status = 0;
            clearInterval(ob);
        }
    });

    // 事件监听
    flipBtn.addEventListener('click', flipCard);
    nextBtn.addEventListener('click', nextWord); //固定下一个
    // nextBtn.addEventListener('click', randomWord); //随机下一个
    card.addEventListener('click', flipCard);

    // 触摸设备支持
    let touchStartX = 0;
    let touchEndX = 0;

    card.addEventListener('touchstart', e => {
        touchStartX = e.changedTouches[0].screenX;
    });

    card.addEventListener('touchend', e => {
        touchEndX = e.changedTouches[0].screenX;
        const swipeDistance = touchEndX - touchStartX;
        
        if (Math.abs(swipeDistance) > 50) { // 最小滑动距离
            if (swipeDistance > 0) {
                // 向右滑动，显示上一个单词
                currentIndex = (currentIndex - 1 + shuffledWords.length) % shuffledWords.length;
            } else {
                // 向左滑动，显示下一个单词
                currentIndex = (currentIndex + 1) % shuffledWords.length;
            }
            displayWord(currentIndex);
            updateProgress();
        }
    });

    // 键盘支持
    document.addEventListener('keydown', e => {
        console.log(e.code);
        // 上键或空格翻转卡片
        if (['Space','ArrowUp','PageUp'].includes(e.code)) {
            // 空格键翻转卡片
            flipCard();
        } else if (['ArrowRight','ArrowLeft','PageDown','ArrowDown'].includes(e.code)) {
            // 方向键切换单词
            if (['ArrowRight','PageDown','ArrowDown'].includes(e.code)) {
                // 向右键显示下一个单词
                currentIndex = (currentIndex + 1) % shuffledWords.length;
            } else {
                // 向左键显示上一个单词
                currentIndex = (currentIndex - 1 + shuffledWords.length) % shuffledWords.length;
            }
            displayWord(currentIndex);
            updateProgress();
        }else if (['Tab','Enter'].includes(e.code)) {
            // 全屏显示
            // if(global.fullscreen == 1){
            //     global.fullscreen = 0;
            //     if(document.exitFullScreen) {
            //         document.exitFullScreen();
            //     } else if(document.mozCancelFullScreen) {
            //         document.mozCancelFullScreen();
            //     } else if(document.webkitExitFullscreen) {
            //         document.webkitExitFullscreen();
            //     } else if(document.msExitFullscreen) {
            //         document.msExitFullscreen();
            //     }
            // }else if(global.fullscreen == 0){
            //     global.fullscreen = 1;
            //     var elem = document.documentElement;
            //     if (elem.requestFullscreen) {
            //         elem.requestFullscreen();
            //     } else if (elem.webkitRequestFullscreen) {
            //         elem.webkitRequestFullscreen();
            //     } else if (elem.msRequestFullscreen) {
            //         elem.msRequestFullscreen();
            //     }
            // }
        }

        // if (['Tab','Enter'].includes(e.code)) {
        //     console.log("阻止提交");
        //     return false;
        // }
    });

    // 初始化
    initializeWords();

    progressSpan.addEventListener('click',function(){
        // 把.controls显示出来
        document.querySelector(".controls").style.display = "block"
    });
});

// 检测翻页笔
document.onkeydown = function(e){
    console.log("外部监听："+e.keyCode);
    if(e.keyCode == 9){
        // 按6次退出全屏
        if(global.fullscreen == 1){
            global.fullscreen = 0;
            if(document.exitFullScreen) {
                document.exitFullScreen();
            } else if(document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if(document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if(document.msExitFullscreen) {
                document.msExitFullscreen();
            }
        }else if(global.fullscreen == 0){
            global.fullscreen = 1;
            // 按3次全屏模式
            var elem = document.documentElement;
            if (elem.requestFullscreen) {
                elem.requestFullscreen();
            } else if (elem.webkitRequestFullscreen) {
                elem.webkitRequestFullscreen();
            } else if (elem.msRequestFullscreen) {
                elem.msRequestFullscreen();
            }
        }
    }
    if([9,13,33,34,38,40,66,27].includes(e.keyCode)){
        console.log("阻止提交");
        return false;
    }
}